<template>
  <div class="login-container">
    <div class="login-content">
      <div class="login-header">
        <h3 class="title">{{ title }}</h3>
      </div>
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
        <el-tabs v-model="loginForm.grantType" class="login-tab">
          <el-tab-pane v-for="(item,index) in localDict.grant_type" v-if="authModel.grantTypes.includes(item.value)"
                       :key="index" :label="item.label" :name="item.value"/>
        </el-tabs>
        <el-form-item v-if="authModel.tenant" prop="tenantName">
          <el-autocomplete v-model="loginForm.tenantName" :fetch-suggestions="handleSearch" placeholder="请选择租户"
                           popper-class="my-autocomplete" style="width: 100%" @select="handleSelect">
            <template v-slot:prefix>
              <svg-icon class="el-input__icon input-icon" icon-class="m_company"/>
            </template>
            <template v-slot:default="scope">
              <div>{{ scope.item.name }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" auto-complete="off" placeholder="账号" type="text">
            <template v-slot:prefix>
              <svg-icon class="el-input__icon input-icon" icon-class="user"/>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" auto-complete="off" placeholder="密码" show-password
                    type="password" @keyup.enter.native="handleLogin">
            <template v-slot:prefix>
              <svg-icon class="el-input__icon input-icon" icon-class="password"/>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="captcha.enable" prop="code">
          <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" style="width: 63%"
                    @keyup.enter.native="handleLogin">
            <template v-slot:prefix>
              <svg-icon class="el-input__icon input-icon" icon-class="validCode"/>
            </template>
          </el-input>
          <div class="login-code">
            <img :src="captcha.img" class="login-code-img" @click="getCode" alt=""/>
          </div>
        </el-form-item>
      </el-form>
      <div style="width:100%;">
        <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
        <el-button :loading="loading" size="small" style="width:100%;" type="primary"
                   @click.native.prevent="handleLogin">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div v-if="authModel.register" style="float: right;">
          <router-link :to="'/register'" class="link-type">立即注册</router-link>
        </div>
      </div>
    </div>
    <!--  底部  -->
    <div class="login-footer">
      <span>Copyright © {{ year }} {{ author }} All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import {getCodeImg, init} from "@/api/auth";
import {decrypt, encrypt} from '@/utils/jsencrypt'

export default {
  name: "Login",
  data() {
    return {
      loading: false,
      year: process.env.VUE_APP_YEAR,
      title: process.env.VUE_APP_TITLE,
      author: process.env.VUE_APP_AUTHOR,
      codeUrl: "",
      authModel: {
        grantTypes: []
      },
      captcha: {
        img: "",
        uuid: '',
        enable: false,
      },
      loginForm: {
        code: "",
        uuid: "",
        username: "admin",
        password: "admin123",
        grantType: "password",
        rememberMe: false,
      },
      loginRules: {
        username: [
          {required: true, trigger: "blur", message: "请输入您的账号"}
        ],
        password: [
          {required: true, trigger: "blur", message: "请输入您的密码"}
        ],
        code: [{required: true, trigger: "change", message: "请输入验证码"}]
      },
      localDict: {
        grant_type: []
      },
      redirect: undefined
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    this.getLocalDict()
    this.getAuthInit();
    this.getCookie();
  },
  methods: {
    async getLocalDict() {
      await this.getStaticData('system-grant-type').then(res => {
        this.localDict.grant_type = res.data
        this.$set(this.loginForm, "grantType", res.data[0].value)
      })
    },
    getAuthInit() {
      init().then(res => {
        this.authModel = res.data
        this.captcha = res.data.captcha
      }).catch(() => {
        this.$message.info("正在获客户端取授权信息，请稍后")
        setTimeout(() => this.getAuthInit(), 15 * 1000)
      })
    },
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.data.captchaEnabled === undefined ? true : res.data.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.data.img;
          this.loginForm.uuid = res.data.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    handleSearch(queryString, cb) {
      const restaurants = this.authModel.tenants;
      console.log(restaurants)
      // const results = queryString ? restaurants.filter(this.handleFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(restaurants);
    },
    handleFilter(queryString) {
      return (restaurant) => {
        console.log(restaurant)
        return (restaurant.label.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      this.$set(this.loginForm, 'tenantId', item.code)
      this.$set(this.loginForm, 'tenantName', item.name)
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, {expires: 30});
            Cookies.set("password", encrypt(this.loginForm.password), {expires: 30});
            Cookies.set('rememberMe', this.loginForm.rememberMe, {expires: 30});
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }
          this.$store.dispatch("Login", {
            tenantId: this.loginForm.tenantId,
            clientId: this.authModel.clientId,
            grantType: this.loginForm.grantType,
            password: this.loginForm
          }).then(() => {
            this.$router.push({path: this.redirect || "/"});
          }).catch(e => {
            this.$modal.alertError(e.message)
            this.loading = false;
            if (this.captcha.enable) {
              this.getCode();
            }
          });
        }
      });
    }
  }
};
</script>

<style lang="scss" rel="stylesheet/scss">
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url('../assets/images/login-background.jpg');
  background-size: cover;
}

.login-content {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;

  .login-header {
    width: 100%;
    height: 60px;
    text-align: center;


    .title {
      color: #707070;
      margin: 10px auto;
      line-height: 40px;
      font-size: 25px;
      font-weight: 450;
    }

    .lang-select {
      width: 60px;
    }
  }

  .el-input {
    height: 40px;

    input {
      height: 40px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 40px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial, serif;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 40px;
  padding-left: 12px;
}
</style>
